/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tlr.device.rest;

import com.tfb.rong.Device;
import com.tfb.service.UserAssessmentI;
import static com.tfb.service.utility.HttpUtil.getUserDBID;
import com.tlr.device.model.AirBox;
import com.tlr.device.model.Result;
import com.tlr.device.service.AirMeasureDevice;
import com.tlr.device.service.DeviceDatabaseService;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Path("/air_measure")
public class AirMeasureResource extends AirDeviceResource {

    private static final Logger log = Logger.getLogger(AirMeasureResource.class);
    @Context
    ServletContext context;

    @Override
    protected synchronized void initDatabaseService() {
        if (deviceService == null || userService == null) {
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
            if (deviceService == null) {
                deviceService = (DeviceDatabaseService) ac.getBean("deviceDatabaseService");
            }
            if (userService == null) {
                userService = (UserAssessmentI) ac.getBean("userAssessmentService");
            }
        }
    }

    @Path("/aqi")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Override
    public Result<JsonNode> getAQI() {
        return super.getAQI();
    }

    @Path("/edit_bind")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Result<String> editBindDevice(@Context HttpServletRequest request, String message) {
        return super.doEditBindDevice(request, message);
    }

    @Path("/add_bind")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Result<String> bindDevice(@Context HttpServletRequest request, String message) {
        return super.doBindDevice(request, message, "空气测量仪", 3);
    }

    @Path("/last_data")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<AirBox>> getLastAirMeasureInfoList() throws IOException {
        try {
            // Get all active air devices for map_info
            initDatabaseService();
            List<Device> devices = deviceService.getAllDevice(3, 1);
            Map<String, Device> macList = new HashMap<>();
            for (Device device : devices) {
                macList.put(device.getDevicemac(), device);
            }
            List<AirBox> boxes = new AirMeasureDevice().getDeviceListLastData(macList);
            return new Result<>(0, "成功", boxes);
        } catch (Exception e) {
            log.error(e.fillInStackTrace());
            return new Result<>(500, "获取设备列表失败");
        }
    }

    @Path("/last_bind_data")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<AirBox>> getLastBindAirMeasureInfoList(@Context HttpServletRequest request) throws IOException {
        try {
            // Get all active air devices for map_info
            initDatabaseService();
            String userID = getUserDBID(request);
            List<Device> devices = deviceService.getDeviceMapper().selectDeviceWithBindedInfoByUserIDAndDeviceType(userID, 3);
            Map<String, Device> macList = new HashMap<>();
            for (Device device : devices) {
                macList.put(device.getDevicemac(), device);
            }
            List<AirBox> boxes = new AirMeasureDevice().getDeviceListLastData(macList);
            return new Result<>(0, "成功", boxes);
        } catch (Exception e) {
            log.error(e.fillInStackTrace());
            return new Result<>(500, "获取用户空气测量仪列表失败");
        }
    }

    @Path("/day_history/{mac}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<AirBox>> getAirMeasureDayData(@PathParam("mac") String mac,
                                                     @QueryParam("data_type") String dataType) throws IOException {
        try {
            return new Result<>(0, "成功", new AirMeasureDevice().getDeviceDayHistoryData(mac, dataType));
        } catch (IOException ex) {
            log.error(ex.fillInStackTrace());
            return new Result<>(500, "读取空气测量仪历史信息失败");
        }
    }

    @Path("/hour_history/{mac}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<AirBox>> getAirMeasureHourData(@PathParam("mac") String mac,
                                                      @QueryParam("data_type") String dataType) throws IOException {
        try {
            return new Result<>(0, "成功", new AirMeasureDevice().getDeviceHourHistoryData(mac, dataType));
        } catch (IOException ex) {
            log.error(ex.fillInStackTrace());
            return new Result<>(500, "读取空气测量仪历史信息失败");
        }
    }

    @Path("/import_device")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<?> importAirDeviceIntoDatabase() {
        try {
            initDatabaseService();
            List<AirBox> boxes = new AirMeasureDevice().getDeviceListLastData();
            for (AirBox box : boxes) {
                Device device = new Device();
                device.setDevicemac(box.getDevice_mac());
                device.setAddress(box.getDevice_city());
                if (deviceService.getDeviceByMac(box.getDevice_mac()) == null) {
                    deviceService.addDevice(device);
                }
            }

        } catch (IOException ex) {
            log.error(ex.fillInStackTrace());
            return new Result<>(500, "导入数据失败");
        }
        return new Result<>(0, "成功导入");
    }

    @Path("/update_position")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Override
    public Result<String> updatePosition(String message) {
        return super.updatePosition(message);
    }
}
